<?php

namespace PhpSeverless;

use Adoy\FastCGI\Client;

class FastCGIClient
{
    /**
     * @var \Adoy\FastCGI\Client
     */
    public $client;

    public $host = '127.0.0.1';

    public $port = '9001';

    public $root = '';

    public function __construct($options = [])
    {
        foreach ($options as $key => $value) {
            if ($key == 'root') {
                $value = realpath($value);
            }
            $this->$key = $value;
        }

        $this->client = new Client($this->host, $this->port);
    }

    public function request(Request $request)
    {
        $headers = $request->headers;
        $scheme = $request->scheme;
        $script = $request->script;
        $method = $request->method;
        $remote_addr = $request->remote_addr;
        $query_string = $request->query_string;
        $request_uri = $request->request_uri;
        $body = $request->body;
        $pathinfo = $request->pathinfo;

        $root = $this->root;

        $filename = realpath($root . $script);
        if (strpos($filename, $root) !== 0) {
            $filename = $root . '/index.php';
        }

        $params = [
            'SERVER_SOFTWARE'   => 'php/fastcgiclient',
            'GATEWAY_INTERFACE' => 'CGI/1.1',
            'SERVER_PROTOCOL'   => 'HTTP/1.1',
            'SERVER_PORT'       => '80',

            'DOCUMENT_ROOT'     => $root,
            'REQUEST_SCHEME'    => $scheme,
            'SCRIPT_FILENAME'   => $filename,
            'SCRIPT_NAME'       => $script,
            'REMOTE_ADDR'       => $remote_addr,
            'QUERY_STRING'      => $query_string,
            'REQUEST_URI'       => $request_uri,
            'REQUEST_METHOD'    => $method,
            'PHP_SELF'          => $script,
            'PATH_INFO'         => $pathinfo,
        ];

        // 转大写
        foreach ($headers as $name => $value) {
            if (in_array($name, array('content-type', 'content-length'), true)) {
                $name = str_replace("-", "_", strtoupper($name));
            } else {
                $name = 'HTTP_' . str_replace("-", "_", strtoupper($name));
            }
            $params[$name] = $value;
        }

        // 修正长度
        if ($body) {
            $params['CONTENT_LENGTH'] = strlen($body);
        }

        $raw_response = $this->client->request($params, $body);

        return $raw_response;
    }

}
